const childProcess = require('child_process');
const path = require('path');
const fs = require('fs');
const http = require('http')

const curl = async (url) => {
    return new Promise((resolve, reject) => {
        http.get(url,function(res){  //发送get请求
            var html=''
            res.on('data',function(data){
                html += data  //字符串的拼接
            })
            res.on('end',function(){
                resolve(html)
            })
        }).on('error',function(){
            resolve('{}')
        })
    });
};
const readdir = async (dir) => {
    return new Promise((resolve, reject) => {
        fs.readdir(dir, (err, files) => {
            if (err) {
                reject(err);
            } else {
                resolve(files);
            }
        });
    });
};
const copyFile = async (path, destPath) => {
    return new Promise((resolve, reject) => {
        fs.copyFile(path, destPath, (err) => {
            if (err) reject(err);
            else resolve();
        });
    });
};
const deleteFile = async (file) => {
    return new Promise((resolve, reject) => {
        fs.unlink(file, (err) => {
            resolve();
            // if (err) reject(err);
            // else resolve();
        });
    });
};
const exists = async (file) => {
    return new Promise( (res, rej) => {
        fs.exists(file, exists => {
            if (exists) {
                res(1);
            } else {
                res(0);
            }
        });
    })
};
const mkdirRecuse = (dir, callback) => {
    fs.exists(dir, exists => {
        if (exists) {
            callback();
        } else {
            mkdirRecuse(path.dirname(dir), function () {
                fs.mkdir(dir, callback);
            });
        }
    });
};
const stat = async (file) => {
    return new Promise((resolve, reject) => {
        fs.stat(file, (err, stat) => {
            if (err) reject(err);
            else resolve(stat);
        });
    });
};
const mkdir = async (dir) => {
    return new Promise(res => {
        mkdirRecuse(dir, function () {
            res();
        });
    });
};
const writeFile = async (file, txt) => {
    return new Promise((resolve, reject) => {
        fs.writeFile(file, txt, err => {
            if (err) reject(err);
            else resolve();
        });
    });
};
/**
 * ffmpeg计算媒体时长
 */
const cal_media_length = async (mediaFile) => {
    return new Promise((resolve, reject) => {
        childProcess.exec(
            'ffmpeg -i ' + mediaFile,
            {},
            (err, stdout, stderr) => {
                if(stderr.match(/Duration: (\d{2}:\d{2}:\d{2}\.?\d*)/)){
                    let time_str = stderr.match(/Duration: (\d{2}:\d{2}:\d{2}\.?\d*)/)[1]

                    // 最后不到1s的部分
                    let mini_seconds = 0
                    if(time_str.split('.').length > 1) {
                        mini_seconds = Number('0.' + time_str.split('.')[1])
                        time_str = time_str.split('.')[0]
                    }

                    const time_str_arr = time_str.split(':')
                    let seconds = 0;
                    for(i=time_str_arr.length-1; i>=0; i--){
                        seconds += Math.pow(60, (time_str_arr.length-1 - i)) * Number(time_str_arr[i])
                    }
                    resolve(seconds + mini_seconds)
                } else {
                    resolve(0)
                }
            }
        );
    });
};
const call_ffmpeg = async (cmd) => {
    return new Promise((resolve, reject) => {
        childProcess.exec(
            'ffmpeg ' + cmd,
            {},
            (err, stdout, stderr) => {
                // console.log('err:***', err)
                // console.log('stdout:***', stdout)
                // console.log('stderr:***', stderr)
                resolve()
            }
        );
    });
};
const sleep = async (milisecond) => {
    return new Promise(resolve => {
        setTimeout(resolve, milisecond);
    });
};

module.exports = { curl, readdir, copyFile, deleteFile, exists, mkdir, stat, writeFile, cal_media_length, call_ffmpeg, sleep };
